package cn.spring.ly.config.shiro.realm;

import java.util.Set;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.spring.ly.entity.SysUser;
import cn.spring.ly.service.SysUserService;
import cn.spring.ly.util.MD5Utils;

public class SysUserRealm extends AuthorizingRealm {

	@Autowired
	SysUserService userService;
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("--------权限设置方法-------");
		// 用户登录成功 设置权限信息
		String username = (String)principals.getPrimaryPrincipal();
		//用户权限
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Set<String> stringPermissions = userService.getUserPressm(username);
//		info.setRoles(roles);
		info.setStringPermissions(stringPermissions );
		return info;
	}

	/**
	 *  用户身份验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		System.out.println("————身份认证方法————");
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

		QueryWrapper<SysUser> queryWapper = new QueryWrapper<SysUser>();
		queryWapper.eq(SysUser.USERNAME, token.getUsername());
		// 从数据库获取对应用户名密码的用户
		SysUser user = userService.getOne(queryWapper);
		if (null == user) {
			throw new AccountException("帐号不存在");
		} 
//		else if (!user.getPassword().equals(
//					// MD5Utils.getPwd(new String((char[]) token.getCredentials()))
//					new SimpleHash("md5", new String((char[]) token.getCredentials())).toHex()  
//				)) {
//			throw new AccountException("密码不正确");
//		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(), 
				user.getPassword(), 
				getName());
		return info;
	}
}
